import { JsonPipe } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  DestroyRef,
  inject,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
  NonNullableFormBuilder,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { expand } from '@core/animations';
import { CharacterSelectorComponent } from './character-selector.component';

@Component({
  selector: 'app-character-selector-demo',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    JsonPipe,
    CharacterSelectorComponent,
  ],
  templateUrl: './character-selector-demo.component.html',
  styleUrl: './character-selector-demo.component.scss',
  animations: [expand],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CharacterSelectorDemoComponent {
  private fb = inject(NonNullableFormBuilder);
  private destroyRef = inject(DestroyRef);

  form = this.fb.group({
    character: ['', Validators.required],
    reason: ['', Validators.required],
  });

  constructor() {
    // clear reason textarea on deselecting a character
    this.form
      .get('character')!
      .valueChanges.pipe(
        takeUntilDestroyed(this.destroyRef),
      )
      .subscribe(
        (name) =>
          !name && this.form.get('reason')!.setValue(''),
      );
  }

  updateFormDisabledState(target: EventTarget | null) {
    if (!(target instanceof HTMLInputElement)) return;

    if (target.checked) {
      this.form.get('character')!.disable();
      this.form.get('reason')!.disable();
    } else {
      this.form.get('character')!.enable();
      this.form.get('reason')!.enable();
    }
  }
}

export default CharacterSelectorDemoComponent;
